/**
 * ConnectionKeepAliveStrategyImpl.java<br>
 *
 * @author aaronwong.sd@foxmail.com
 * @version 下午3:11:46
 */
package com.mc.httpclient;

import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;

import com.mc.util.PropertyUtils;

/**
 * 链接保活策略
 *
 * @author aaronwong.sd@foxmail.com
 */
public class ConnectionKeepAliveStrategyImpl implements ConnectionKeepAliveStrategy {
	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.apache.http.conn.ConnectionKeepAliveStrategy#getKeepAliveDuration(org
	 * .apache.http.HttpResponse, org.apache.http.protocol.HttpContext)
	 */
	@Override
	public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
		// Honor 'keep-alive' header
		HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
		while (it.hasNext()) {
			HeaderElement he = it.nextElement();
			String param = he.getName();
			String value = he.getValue();
			if (value != null && param.equalsIgnoreCase("timeout")) {
				try {
					return Long.parseLong(value) * 1000;
				} catch (NumberFormatException ignore) {
				}
			}
		}
		PropertyUtils config = PropertyUtils.getInstance();
		HttpHost target = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
		String domain = config.getStringValue("httpclient", "default.domain");
		int k1 = config.getIntValue("httpclient", "default.domain.keepAlive");
		int k2 = config.getIntValue("httpclient", "default.keepAlive");
		if (domain.equalsIgnoreCase(target.getHostName())) {
			return k1 * 1000;
		} else {
			return k2 * 1000;
		}
	}
}
